package com.dayuanit.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.dayuanit.dao.DetailDao;
import com.dayuanit.domain.Detail;

public class DetailDaoImpl implements DetailDao {

	public int add(Detail detail, Connection conn) {
		String sql = "insert into atm_detail(user_id, amount, desc_msg, card_num, create_time) values(?, ?, ?, ?, now());";
		System.out.println(sql);

		PreparedStatement psm = null;
		int rows = 0;

		try {
			psm = conn.prepareStatement(sql);
			psm.setInt(1, detail.userId);
			psm.setInt(2, detail.amount);
			psm.setString(3, detail.descMsg);
			psm.setString(4, detail.cardNum);
			
			rows = psm.executeUpdate();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != psm) {
					psm.close();
				}
			} catch (SQLException se) {
				se.printStackTrace();
			}

		}

		return rows;
	}

	public List<Detail> query(String cardNum, Connection conn) {

		String sql = "select id, user_id, amount, card_num, desc_msg, create_time from atm_detail where card_num = ?;";
		System.out.println(sql);

		PreparedStatement psm = null;
		ResultSet rs = null;

		List<Detail> details = new ArrayList<Detail>();
		Detail detail = null;

		try {
			psm = conn.prepareStatement(sql);
			psm.setString(1, cardNum);
			rs = psm.executeQuery();

			while (rs.next()) {
				int id = rs.getInt("id");
				int userId = rs.getInt("user_id");
				int amount = rs.getInt("amount");
				String descMsg = rs.getString("desc_msg");
				Timestamp tt = rs.getTimestamp("create_time");

				detail = new Detail();
				detail.id = id;
				detail.userId = userId;
				detail.cardNum = cardNum;
				detail.amount = amount;
				detail.descMsg = descMsg;
				detail.createTime = new Date(tt.getTime());

				details.add(detail);

			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != rs) {
					rs.close();
				}
				if (null != psm) {
					psm.close();
				}
			} catch (SQLException se) {
				se.printStackTrace();
			}

		}

		return details;

	}
}